#' Batch Calculate JIP-test Parameters
#'
#' This function applies the JIP-test analysis to a combined data frame of
#' induction curves. It splits the data by sample (as indicated by the `SOURCE`
#' column), computes JIP parameters for each sample using `jip_comp`, and
#' combines the results into a single data frame.
#'
#' @param df A data frame (typically the output of `read_all_induction`). It
#'   must contain the `SOURCE` column and all other columns required by the
#'   `jip_comp` function.
#' @param use_PAM A logical value. If `TRUE`, the function uses the PAM
#'   fluorescence signal (`FLUOR` column) for calculations. If `FALSE` (the
#'   default), it uses the continuous DC signal (`DC` column).
#' @param verbose A logical value. If `TRUE`, the function will print the name
#'   of each sample as it is being processed. Defaults to `FALSE`.
#'
#' @return A data frame (or `data.table`) containing the JIP-test parameters
#'   for each sample. Each row represents a sample.
#'
#' @seealso \code{\link{jip_comp}}, \code{\link{read_all_induction}}
#'
#' @examples
#' \dontrun{
#' library(jiptest)
#'
#' # Step 1: Read all induction files from a directory
#' combined_data = read_all_induction("path/to/your/data_directory")
#'
#' # Step 2: Perform JIP-test analysis on all samples using the DC signal
#' jip_results = jip_test(combined_data, use_PAM = FALSE)
#'
#' # View the results
#' head(jip_results)
#' }
#'
#' @importFrom data.table rbindlist
#' @export

jip_test = function(df, use_PAM = FALSE, verbose = FALSE) {

  # Input validation
  if (!is.data.frame(df)) {
    stop("The first argument `df` must be a data frame. Did you intend to use `read_all_induction()` first?")
  }

  if (!"SOURCE" %in% colnames(df)) {
    stop("The input data frame `df` must contain a 'SOURCE' column.")
  }

  # Split data by the 'SOURCE' column
  split_data = split(df, df$SOURCE)

  if (length(split_data) == 0) {
    warning("No data to process. The 'SOURCE' column may be empty.")
    return(data.frame())
  }

  # Process each sample with jip_comp
  list_df = lapply(names(split_data), function(source_name) {
    if (verbose) {
      message("Processing sample: ", source_name)
    }
    # Extract data for the current sample
    sample_data = split_data[[source_name]]
    # Call jip_comp with the appropriate use_PAM value
    jip_comp(sample_data, use_PAM = use_PAM)
  })

  # Combine all results into a single data frame
  if (length(list_df) > 0) {
    ojip_data = data.table::rbindlist(list_df)
    # Convert back to a regular data frame if preferred (optional)
    # ojip_data = as.data.frame(ojip_data)
  } else {
    ojip_data = data.frame()
  }

  return(ojip_data)
}

